package com.wll.study.algotiyhm.about_linklode;

/**
 * 检测链表回环
 *
 * @author wull
 */
public class ListNodeDetectLoopback {
    /**
     * 给定一个链表，如果它是有环链表，实现一个算法返回环路的开头节点。
     * https://leetcode-cn.com/problems/linked-list-cycle-lcci/
     * @param head 链表头指针
     * @return 回环头指针
     */
    public ListNode detectCycle(ListNode head){
        if (head == null){return null;}
        ListNode slow = head,fast = head;
        while (slow != null){
            if (slow == fast &&slow != head){
                return slow;
            }
            if (fast == null && fast != head){
                break;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return null;
    }
}
